<template>
  <div ref="imageDom" class="app-container">
    <el-row style="margin-bottom:20px" type="flex" justify="space-between" align="middle">
      <div>
        <el-radio-group
        style="margin-right:20px"
        size="small"
        v-model="date">
          <el-radio-button
            v-for="item in timeList"
            :label="item.id"
            :key="item.id">
            {{item.name}}
          </el-radio-button>
        </el-radio-group>
        <el-date-picker
          size="small"
          v-model.number="time"
          type="datetimerange"
          value-format="timestamp"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </div>
      <div class="down">
        <el-button type="text" @click="handlePrint">
          <i class="el-icon-download"></i>
        </el-button>
      </div>
    </el-row>
    <el-row style="margin-bottom:20px" type="flex" justify="space-between" class="stream">
      <div class="left">
        <p>流水数据 <span>（2020-03-12 ~ 2020-03-17）</span></p>
        <el-table
          :data="streamData"
          border
          style="width: 100%"
          >
          <el-table-column
            prop="name"
            label="指标"
            align="center"
            >
          </el-table-column>
          <el-table-column
            prop="address"
            align="center"
            label="合计">
          </el-table-column>
        </el-table>
      </div>
      <div class="left">
        <p>流水数据 <span>（2020-03-12 ~ 2020-03-17）</span></p>
        <!-- <div id="echart" style="background:#fff;padding:16px;margin:32px 0; width:100%;height:100%">
        </div> -->
        <chart :options="options" width="100%" height="385px"></chart>
      </div>
    </el-row>
    <el-row type="flex" justify="space-between">
      <div class="statistics-list" v-for="(item,index) in statistics" :key="index">
        <p>销售额 <span>（2020-03-12~ 2020-03-17 ）</span></p>
        <count-to :start-val="0" :end-val="item.price" :duration="3000" class="card-panel-num" />
        <div>
          <p>环比：<span>{{item.h}}</span></p>
           <p>同比：<span>{{item.t}}</span></p>
        </div>
      </div>
    </el-row>
  </div>
</template>

<script>
import CountTo from 'vue-count-to'
import chart from '@/components/Charts/Keyboard'
import html2canvas from 'html2canvas'
import { randomString } from '@/utils'
// 全部引入
// var echarts = require('echarts')
export default {
  name: 'DataStatistics',
  components: { chart, CountTo },
  data() {
    return {
      date: null,
      time: null,
      timeList: [],
      streamData: [ // 流水数据
        {
          date: '2016-05-02',
          name: '销售总额（¥）',
          address: '234567'
        },
        {
          date: '2016-05-02',
          name: '生成订单数',
          address: '234567'
        },
        {
          date: '2016-05-02',
          name: '支付成功总额（¥）',
          address: '234567'
        },
        {
          date: '2016-05-02',
          name: '支付成功订单数',
          address: '234567'
        },
        {
          date: '2016-05-02',
          name: '优惠券抵扣金额（¥）',
          address: '234567'
        },
        {
          date: '2016-05-02',
          name: '客单价（¥）',
          address: '234567'
        },
        {
          date: '2016-05-02',
          name: '退款金额（¥）',
          address: '234567'
        }
      ],
      options: {
        backgroundColor: '#fff',
        // title: {
        //   text: ''
        // },
        tooltip: {},
        xAxis: {
          axisLine: {
            show: false // 隐藏坐标轴线
          },
          type: 'category',
          splitLine: { show: false },
          symbol: 'none', // 这句就是去掉点的
          data: [1, 23, 45, 66],
          axisTick: {
            // alignWithLabel: true
          },
          axisLabel: {
            interval: 0
            // rotate: 40
          }
        },

        yAxis: {
          axisLine: {
            show: false
          }
          // data: this.receive
        },
        series: [
          {
            name: '领取数量',
            type: 'bar',
            data: [1, 23, 45, 66],
            color: ['#396aff'],
            lineStyle: {
              width: 4
            }
          }
        ]
      },
      statistics: [
        {
          price: 7347,
          h: '50.13%',
          t: '50.13%'
        },
        {
          price: 7347,
          h: '50.13%',
          t: '50.13%'
        },
        {
          price: 7347,
          h: '50.13%',
          t: '50.13%'
        },
        {
          price: 7347,
          h: '50.13%',
          t: '50.13%'
        }
      ]
    }
  },
  computed: {
  },
  watch: {

  },
  created() {
    this.setTimeData()
  },
  mounted() {
  },
  methods: {
    handlePrint() {
      // window.print()
      window.scrollTo(0, 0)
      const loading = this.$loading({
        lock: true,
        text: '努力生成中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // this.$refs[formName].resetFields()
      const canvasBox = this.$refs.imageDom
      this.$nextTick(() => {
        // 手动创建一个 canvas 标签
        const canvas = document.createElement('canvas')
        // 获取父标签，意思是这个标签内的 DOM 元素生成图片
        // 获取父级的宽高
        const width = parseInt(window.getComputedStyle(canvasBox).width)
        const height = parseInt(window.getComputedStyle(canvasBox).height)

        // let {width, height} = canvasBox.getBoundingClientRect();
        const dpr = window.devicePixelRatio || 1
        // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
        canvas.width = width * dpr
        canvas.height = height * dpr
        canvas.style.width = width + 'px'
        canvas.style.height = height + 'px'

        const context = canvas.getContext('2d')
        context.scale(dpr, dpr)
        const rectObject = canvasBox.getBoundingClientRect()
        const eleft = rectObject.left
        const etop = rectObject.top
        context.translate(-eleft, -etop)
        // const sidebarStatus = Cookies.get('sidebarStatus') === '0' ? 2 : 5
        html2canvas(this.$refs.imageDom,
          {
            useCORS: true, // 【重要】开启跨域配置
            // allowTaint: true, // 允许跨域图片
            tainttest: true, // 检测每张图片都已经加载完成
            logging: false,
            ...canvas,
            // scrollY: Number(`-${this.scrollYheight || 0}`),
            scrollX: 0,
            proxy: 'https://app.jiabala.com',
            letterRendering: true
            // backgroundColor: null // null 表示设置背景为透明色
          }
        ).then(canvas => {
          // 转成图片，生成图片地址
          loading.close()
          const imgUrl = canvas.toDataURL('image/png')
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = imgUrl
          link.download = `数据统计_${randomString(5)}`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          // console.log(imgUrl)
        })
      })
    },
    // 获得某月的天数
    getMonthDays(myMonth, nowYear) {
      var monthStartDate = new Date(nowYear, myMonth, 1)
      var monthEndDate = new Date(nowYear, myMonth + 1, 1)
      var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24)
      return days
    },
    setTimeData() {
      const end = new Date()
      const start = new Date()
      const nowDayOfWeek = start.getDay() // 今天本周的第几天
      const nowDay = start.getDate() // 当前日
      const nowMonth = start.getMonth() // 当前月
      const nowYear = start.getFullYear() // 当前年
      const lastMonthDate = new Date() // 上月日期
      lastMonthDate.setDate(1)
      lastMonthDate.setMonth(lastMonthDate.getMonth() - 1)
      const lastYear = lastMonthDate.getYear()
      const lastMonth = lastMonthDate.getMonth()
      // 上月开始时间
      const monthStart = new Date(nowYear, lastMonth, 1)
      // 上月结束时间
      const monthEnd = new Date(nowYear, lastMonth, this.getMonthDays(lastMonth, nowYear))
      // 今天0点
      const todayStart = new Date(new Date(start.toLocaleDateString()).getTime())
      // 今天23点
      const todayEnd = new Date(new Date(start.toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
      // 本周第一天
      const weekStart = new Date(start.getFullYear(), nowMonth, nowDay + 1 - nowDayOfWeek || 7)
      // 本周最后一天
      const weekEnd = new Date(start.getFullYear(), nowMonth, nowDay + 7 - nowDayOfWeek || 7)
      // 本月
      start.setTime(new Date(start.getFullYear(), start.getMonth(), 1))
      this.timeList = [
        {
          name: '今日',
          id: `${todayStart.valueOf()},${new Date(end).valueOf()}`
        },
        {
          name: '本周',
          id: `${weekStart.valueOf()},${weekEnd.valueOf() + 24 * 60 * 60 * 1000 - 1}`
        },
        {
          name: '本月',
          id: `${new Date(start).valueOf()},${new Date(end).valueOf()}`
        },
        {
          name: '上月',
          id: `${monthStart.valueOf()},${monthEnd.valueOf()}`
        }
      ]
      this.date = `${todayStart.valueOf()},${new Date(end).valueOf()}`
    }

  }
}
</script>
<style lang="scss" scoped>
  .el-button{
    font-size: 22px;
  }
  .stream{
    margin-bottom: 20px;
    .left{
      padding: 20px;
      width:49%;
      background: #fff;
      transition: all .3S ease-in-out;
      &:hover{
       box-shadow: 0px 0px 10px rgba(129, 129, 129, 0.3);
      }
      >p{
        margin:15px 20px;
        font-size: 18px;
        >span{
          font-size: 14px;
          color: rgb(99, 99, 99);
        }
      }
    }
  }
  .statistics-list{
    cursor: pointer;
    padding: 10px;
    display: flex;
    flex-flow: column;
    justify-content: space-between;
    align-items: center;
    width: 23%;
    min-width: 245px;
    height: 150px;
    background: #fff;
    transition: all .3S ease-in-out;
    &:hover{
      box-shadow: 0px 0px 10px rgba(129, 129, 129, 0.3);
    }
    >p{
      margin:0;
      font-size: 16px;
      >span{
        font-size: 12px;
        color: rgb(99, 99, 99);
      }
    }
    .card-panel-num{
      font-size: 30px;
      font-weight: 600;
    }
    >div{
      display: flex;
      >p{
        &:first-child{
          margin-right: 10px ;
        }
        >span{
          color: red;
        }
      }
    }
  }
</style>
